<template>
  <div>
    <search-form 
      v-if="table_config.isShowSearchForm"
      :formItem="searchFormConfig.form_item || []" 
      :formData="form_data" 
      :formHandler="searchFormConfig.form_handler || [] "
      @callbackComponent="callbackComponent" />
    <slot name="content" ></slot>
    <el-table v-loading="loading" :data="table_data" border stripe style="width: 100%">
      <el-table-column v-if="table_config.checkbox" type="selection" width="55"></el-table-column>
      <template v-for="item in table_config.thead">
        <el-table-column v-if="item.type === 'function'" :prop="item.prop" :label="item.label" :key="item.prop">
          <template slot-scope="scoped" >
            <!-- callback是否存在，存在则执行 -->
            <span v-html="item.callback && item.callback(scoped.row, item.prop)" ></span>
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'slot'" :prop="item.prop" :label="item.label" :key="item.prop" :width="item.width">
          <template slot-scope="scoped" > 
            <slot :name="item.slotName" :data="scoped.row" ></slot>
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'switch'" :prop="item.prop" :label="item.label" :key="item.prop" :width="item.width">
          <template slot-scope="scoped" > 
            <el-switch @change="item.handler && item.handler(scoped.row)" v-model="scoped.row[item.prop]" active-color="#13ce66" inactive-color="#ff4949" :active-value="item.on || true" :inactive-value="item.off || false"></el-switch>
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'image'" :prop="item.prop" :label="item.label" :key="item.prop" :width="item.width" >
          <template slot-scope="scoped" > 
            <img :src="scoped.row[item.prop]" alt="" :width="item.imgWidth || 50">
          </template>
        </el-table-column>
        <el-table-column v-else-if="item.type === 'operation'" :prop="item.prop" :label="item.label" :key="item.prop" :width="item.width">
          <template slot-scope="scoped">
            <template v-if="item.buttonGroup && item.buttonGroup.length > 0">
              <template v-for="button in item.buttonGroup">
                <!-- 事件 -->
                <el-button 
                  v-if="button.event === 'button'"
                  :type="button.type" 
                  :key="button.id" 
                  @click="button.handler && button.handler(scoped.row)" size="small">
                  {{ button.label }}
                </el-button>
                <!-- 路由跳转 -->
                <router-link v-if="button.event === 'link'" :key="button.id" :to="{name: button.name, query: { [button.key]: scoped.row[button.value || 'id'] }}" class="mr-10">
                  <el-button :type="button.type" size="small">{{ button.label }}</el-button>
                </router-link>
              </template>
            </template>
            <template v-if="item.default && item.default.editBtn">
              <el-button v-if="item.default.editBtnEvent" type="primary" size="small" @click="edit(scoped.row.id,item.default.editBreakLink)">编辑</el-button>
              <router-link v-else :to="{name:item.default.editBreakLink,query:{id:scoped.row.id}}" >
                <el-button type="primary" size="small" style="margin-right:10px">编辑</el-button>
              </router-link>
            </template>
            <slot v-if="item.slotName" :name="item.slotName" :data="scoped.row" ></slot>
            <el-button v-if="item.default && item.default.deleteBtn" type="danger" size="small" :loading="scoped.row[item.default.deleteKey || 'id'] == rowId" @click="onDelete(scoped.row[item.default.deleteKey || id])">删除</el-button>
          </template>
        </el-table-column>
        <el-table-column v-else :prop="item.prop" :label="item.label" :key="item.prop"></el-table-column>
      </template>
    </el-table>
    <el-row class="padding-top-30" >
      <el-col :span="4"><div style="padding: 5px"></div></el-col>
      <el-col :span="20">
        <el-pagination
          v-if="table_config.pagination"
          class="pull-right"
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="currentPage"
          :page-sizes="[10, 20, 30, 40]"
          :page-size="10"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { GetTableData, Delete } from "@/api/common.js"
import SearchForm from "@/components/form/search.vue";

export default {
  name: "TableComponent",
  components: {
    SearchForm
  },
  props: {
    config:{type:Object,default:()=>{}},
    searchFormConfig:{type:Object,default:()=>({})},
  },
  watch: {
    config: {
      handler(newValue) {
        this.initConfig()
      },
      immediate: true
    },
    "$store.state.common.table_loadData_flag": {
      handler(newValue) {
        this.loadData();
      }
    }
  },
  data() {
    return {
      rowId: "",
      loading: false,
      table_data: [],
      table_config: {
        thead: [],
        checkbox: true,
        url: "",
        pagination: true,
        data: {},
        isShowSearchForm: true,
        isRequest: true
      },
      total: 0,
      currentPage: 1,
      pageSize: 10,
      pageNumber: 1,
      form_data: {},
    }
  },
  methods: {
    callbackComponent(params) {
      this[params.function](params.data);
    },
    search(data) {
      const searchData = data;
      searchData.pageNumber = 1;
      searchData.pageSize = 10;
      this.requestData(searchData);
    },
    handleSizeChange(val) {
      this.table_config.data.pageSize = val
      this.loadData();
    },
    handleCurrentChange(val) {
      this.table_config.data.pageNumber = val
      this.loadData();
    },
    initConfig() {
      for(let key in this.config) {
        if(Object.keys(this.table_config).includes(key)) {
          this.table_config[key] = this.config[key];
        }
      }
      this.table_config.isRequest && this.loadData();
    },
    loadData() {
      const table_config = this.table_config;
      this.loading = true;
      let data = {
        url: table_config.url,
        data: table_config.data
      }
      GetTableData(data)
        .then((res) => {
          if(res.data) {
            this.table_data = res.data.data
          }
          this.$nextTick(() => {})
          this.total = res.data.total;
          this.loading = false;
        })
        .catch(() =>{this.loading = false;})
    },
    requestData(params = "") {
      // 可以额外进行处理业务逻辑
      if(params) {
        this.table_config.data = params;
      }
      this.loadData()
    },
    onDelete(id) {
      this.$confirm('是否删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.rowId = id;
        let requestData = {
          url: this.table_config.url,
          data: {id}
        }
        Delete(requestData)
          .then((res) => {
            this.$message({
              type: 'success',
              message: res.message
            });
            this.rowId = ""
            this.requestData();
          })
      }).catch((err) => {
        console.log(err)
        this.$message({
          type: 'info',
          message: '已取消删除'
        });  
        this.rowId = "";       
      });
    },
    edit(id, link) {
      this.$router.push({
        name: link,
        query: {id}
      })
    },
  }
}
</script>

<style lang="scss" scoped>

</style>